import json
import os


def parseCombination(combination):
    """
    将元组转换成有序的元组
    :param combination:
    :return:
    """
    return tuple(sorted(list(combination)))


class AccCombinationRecord(object):
    # epoch_com_acc_list其中的每个元素都是一个map，记录着该轮次下不同组合的正确率
    def __init__(self):
        self.epoch_com_acc_list = []

    def getRecord(self, epoch, combination):
        """
        返回对应轮次对应组合的正确率
        :param epoch:轮次
        :param combination:元组类型
        :return:
        """
        order_com = parseCombination(combination)
        order_com_str = str(order_com)
        if self.combinationIsExistInRecord(epoch, order_com):
            return self.epoch_com_acc_list[epoch][order_com_str]
        else:
            return None

    def combinationIsExistInRecord(self, epoch, combination):
        """
        判断某个组合是否已经在某个轮次中出现
        :param epoch:
        :param combination:tuple
        :return:
        """
        if epoch >= len(self.epoch_com_acc_list):
            return False
        order_com = parseCombination(combination)
        order_com_str = str(order_com)
        if order_com_str in self.epoch_com_acc_list[epoch]:
            return True
        else:
            return False

    def addCombinationAcc(self, epoch, combination, acc):
        """
        添加对应轮次的某个组合的正确率
        :param epoch:
        :param combination:
        :param acc:
        :return:
        """
        if epoch >= len(self.epoch_com_acc_list):
            for i in range(epoch - len(self.epoch_com_acc_list) + 1):
                self.epoch_com_acc_list.append({})
        order_com = parseCombination(combination)
        order_com_str = str(order_com)
        self.epoch_com_acc_list[epoch][order_com_str] = acc

# 自定义的 JSON 编码器
class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, AccCombinationRecord):
            return obj.__dict__
        return super().default(obj)


def WriteRecordsToFile(file_path, records):
    # 确保文件所在的目录存在
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        os.makedirs(directory)

    # 将记录序列化为 JSON 字符串
    json_str = json.dumps(records, indent=4, cls=CustomEncoder)

    # 写入文件
    with open(file_path, 'w') as file:
        file.write(json_str)